package fibTests;

public class FibMatrix implements IFib {
	private int iterations;
	
	public FibMatrix() {
		iterations = 0;
	}
	
	@Override
	public int getLastIterationsCounter() {
		return iterations;
	}

	@Override
	//Taken from
	//ru.wikibooks.org
	public long fib(int n)
	{
		iterations = 0;
		int a = 1, ta, 
		b = 1, tb,
		c = 1, rc = 0,  tc,
		d = 0, rd = 1; 
		while (n != 0) { 
			iterations++;
			if ((n & 1) != 0) {
				tc = rc;
				rc = rc*a + rd*c;
				rd = tc*b + rd*d;
			} 
			ta = a; tb = b; tc = c;
			a = a*a  + b*c;
			b = ta*b + b*d;
			c = c*ta + d*c;     
			d = tc*tb+ d*d;
	
			n >>= 1;

		}  
		return rc;
	}

}
